import base64
import string
from urllib.parse import urljoin
import zlib
import re

_base64_alphabet = (string.ascii_uppercase + string.ascii_lowercase +
                    string.digits + '+/')
_plantuml_alphabet = (string.digits + string.ascii_uppercase +
                      string.ascii_lowercase + '-_')
_b64_to_plantuml = bytes.maketrans(
    _base64_alphabet.encode('utf-8'),
    _plantuml_alphabet.encode('utf-8'),
)

server = 'http://192.168.1.157:8889/'


def compress_uml(uml_content):
    compressed_content = zlib.compress(uml_content.encode())
    encoded_content = base64.b64encode(compressed_content).translate(
        _b64_to_plantuml).decode()
    return encoded_content


def get_image_url(uml_content, format='svg'):
    encoded_content = compress_uml(uml_content)
    return urljoin(server, f'{format}/~1{encoded_content}')


def uml_to_img(match):
    url = get_image_url(match.group(1))
    return f'![uml]({url})'


def replace_uml_code(md_content):
    pattern = re.compile(r'```\s*uml(.+?)```', flags=re.S)
    md_content = pattern.sub(uml_to_img, md_content)
    return md_content
